package com.train.mgr.modules.system.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.IdUtil;
import com.train.common.enums.LoginTypeEnum;
import com.train.common.exception.BusinessException;
import com.train.common.model.R;
import com.train.common.model.SysUser;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.StringUtils;
import com.train.mgr.config.redis.RedisUtil;
import com.train.mgr.config.secrity.components.TrainAuthenticationToken;
import com.train.mgr.modules.system.dto.request.UserLoginReqDTO;
import com.train.mgr.modules.system.service.MenuService;
import com.train.mgr.modules.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author cxg
 * @desc 用户授权
 * @date 2023/02/01 16:32
 **/
@RestController
@Slf4j
@RequestMapping("/v1/auth")
@Api( tags = "认证模块")
@RequiredArgsConstructor
public class AuthController {

    private final MenuService menuService;

    private final RedisUtil redisUtil;
    @Autowired
    private AuthenticationManager authenticationManager;

    private final UserService userService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public R<Authentication> login(@RequestBody UserLoginReqDTO userLoginReqDTO) {
        String token = IdUtil.simpleUUID();
        TrainAuthenticationToken unauthenticated =new TrainAuthenticationToken(userLoginReqDTO.getUsername(), userLoginReqDTO.getPassword(),userLoginReqDTO.getUserType(),null,token, LoginTypeEnum.USERNAMELOGIN);
        TrainAuthenticationToken authenticate = null;
        try {
            authenticate = (TrainAuthenticationToken)authenticationManager.authenticate(unauthenticated);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        } catch (AuthenticationException e) {
            log.error("error:" + e.getMessage());
            throw new BusinessException(" e.getMessage())～");
        }
        log.info("login,token:{}",token);
        redisUtil.set(token,authenticate.getUserId(),60*60*24*7);
        return R.succeed(authenticate);
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public R logout(@RequestParam(name = "token",required = true) String token) {
        log.info("logout token:{}",token);
        if(StringUtils.isEmpty(token)){
            throw new BusinessException("token参数值必须手动传入～");
        }
        redisUtil.del(token);
        userService.logout();
        return R.succeed(AuthUtils.getUsername(),"退出登录完成");
    }

//
//    @GetMapping("/study_login")
//    @ApiOperation("学习平台学员登录")
//    public R<Authentication> studyLogin(@RequestParam(name = "username") String username,
//                                        @RequestParam(name = "password") String password) {
//        User dbUser = userService.getByNameAndType(null, username, UserTypeEnum.EMPLOYEE.getCode().toString());
//        if(ObjectUtil.isEmpty(dbUser)){
//            log.info("账号{}不存在",username);
//            return R.succeed(null,"账号不存在");
//        }
//        try {
//            String token = IdUtil.simpleUUID();
//            TrainAuthenticationToken unauthenticated =new TrainAuthenticationToken(username, password,UserTypeEnum.EMPLOYEE.getCode(),null,token, LoginTypeEnum.USERNAMELOGIN);
//            TrainAuthenticationToken authenticate = null;
//            authenticate = (TrainAuthenticationToken)authenticationManager.authenticate(unauthenticated);
//            SecurityContextHolder.getContext().setAuthentication(authenticate);
//            redisUtil.set(token,authenticate.getUserId(),60*60*24);
//            return R.succeed(authenticate);
//        } catch (Exception e) {
//            log.error("error:" + e.getMessage());
//            log.info("账号{},密码{} 验证不正确～",username,password);
//           // throw new BusinessException(" e.getMessage())～");
//            return R.succeed(null,"账号或密码不正确");
//        }
//    }
    /**
     * 获取登陆用户信息
     * @return
     */
    @ApiOperation("获取登陆用户信息")
    @GetMapping("/info")
    public R<SysUser> userInfo() {
        return R.succeed(AuthUtils.getCurrentUser());
    }

    /**
     * 获取路由列表
     *
     * @return
     */
    @ApiOperation("获取路由列表")
    @GetMapping("/routerList")
    public R<List<Tree<Long>>> routerList() {
        return R.succeed(menuService.routerList());
    }


    /**
     * @return

    @ApiOperation("在线用户列表")
    @GetMapping("/onlineUser")
    public R<PageResult<SysUser>> onlineUser(PageParam pageParam) {
        return R.succeed(authService.onlineUser(pageParam));
    }
     */
}
